import { onUnmounted, Ref } from 'vue'
import { Viewer } from '@/types'
import { Widget } from '@/models'

/** 控件初始名称 */
export default function useWidgetName(viewer: Viewer, widgets: Ref<Widget[]>) {
  // 控件拖入计数
  const counter = new Map(Widget.getWidgetOptions().map(item => [item.type, 0]))

  // 控件名称自动计数
  const getWidgetName = (widget: Widget, count: number) => `${widget.option.name}${count}`

  // 设置控件名称
  function setWidgetName(widget: Widget) {
    // 已有名称则中止
    if (widget.name) return

    const list = widgets.value
    let count = (counter.get(widget.type) || 0) + 1
    let name = getWidgetName(widget, count)

    // 如果名称已存在则重新获取
    while (list.some(item => item.name === name)) {
      name = getWidgetName(widget, ++count)
    }

    widget.name = name

    counter.set(widget.type, count)
  }

  // 监听控件拖入
  viewer.$on('widget-drop', setWidgetName)

  // 销毁时解除监听
  onUnmounted(() => {
    viewer.$off('widget-drop', setWidgetName)
  })
}
